<template>
  <div>
    <h3>{{docClassId?$route.meta.title:'文档查看及修改'}}</h3>
    <div class="body">
      <vxe-toolbar>
        <template #buttons>
          <el-row type="flex" :gutter="10" justify="space-between">
            <el-col v-if="!docClassId" :span="4" >
              <div style="display: flex;">
                <el-button-group style="display: flex;">
                  <el-button type="success" icon="el-icon-printer" size="small" @click="exportData">打印或导出</el-button>
                  <el-button type="success" size="small" @click="exportSelectEvent"> {{checkText}} <i class="el-icon-document-checked"></i></el-button>
                </el-button-group>
              </div>
            </el-col>
            <el-col :span="4">
              <el-select v-model="searchForm.docClassId" size="small" filterable clearable placeholder="文档类型">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_docClass" :key="index">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="4" v-if="docClassId!=53">
              <el-select v-model="searchForm.departmentId" size="small" filterable clearable placeholder="选择发布部门">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_regulation_department" :key="index">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="4">
              <el-select v-model="searchForm.empId" size="small" filterable clearable placeholder="选择撰写者">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_emp" :key="index">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="5" v-if="docClassId!=40&&docClassId!=46">
              <el-date-picker size="small" v-model="doubleDate" type="daterange" align="center" unlink-panels style="width: 70%;"
                range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions">
              </el-date-picker>
            </el-col>
            <el-col :span="4" style="display: flex;">
              <el-button type="success" size="small" icon="el-icon-s-promotion" @click="searchSubmit"
                style="margin: 0 10px;">
                搜索</el-button>
              <vxe-button @click="clearTableFilter" status="warning" icon="el-icon-refresh-right"> 清空</vxe-button>
            </el-col>
            <el-col :span="3">
              <vxe-input style="float: right;" v-model.trim.lazy="filterName" type="search" placeholder="快捷检索"
                @input="searchEvent"></vxe-input>
            </el-col>
          </el-row>
        </template>
      </vxe-toolbar>
      <vxe-table resizable ref="XTable" border max-height="800" stripe highlight-hover-row highlight-current-row resizable
        :loading="loading" :data="dataList" @sort-change="sortChange" :export-config="{}">
        <vxe-column field="checkbox" type="checkbox" width="60"></vxe-column>
        <vxe-table-column field="name" title="文档标题" sortable min-width="250"></vxe-table-column>
        <vxe-table-column field="departmentName" v-if="docClassId!=53" title="发布部门" sortable></vxe-table-column>
        <vxe-table-column field="emp" :title="docClassId==40||docClassId==46||docClassId==53?'上传者':'撰写者'" sortable></vxe-table-column>
        <vxe-table-column field="createDate" :title="docClassId==40||docClassId==46||docClassId==53?'发布日期':'创建日期'" sortable></vxe-table-column>
        <vxe-table-column field="openDate" v-if="docClassId!=40&&docClassId!=46" title="开始日期" sortable></vxe-table-column>
        <vxe-table-column field="closeDate" v-if="docClassId!=40&&docClassId!=46" title="截止日期" sortable></vxe-table-column>
        <vxe-table-column field="status" v-if="docClassId!=40&&docClassId!=46" title="状态" sortable width="70"></vxe-table-column>
        <vxe-table-column field="" title="操作" width="180">
          <template #default="{ row }">
            <el-button @click="printModalShow(row)" type="primary" circle size="medium" icon="el-icon-view"></el-button>
            <el-button @click="planEdit(row)" type="primary" circle size="medium" icon="el-icon-edit"></el-button>
            <el-button @click="planDelete(row)" type="primary" circle size="medium" icon="el-icon-delete"></el-button>
          </template>
        </vxe-table-column>
        <vxe-table-column v-if="docClassId==40||docClassId==46" field="memo" title="附件" width="400">
          <template #default="{ row }">
            <div v-loading="row.downloadShow">
              <el-upload
                class="upload-demo"
                action="/regulation/fileUpload"
                :on-change="beforeFileUpload"
                :limit="1"
                :auto-upload="false"
                :show-file-list="false"
                :file-list="fileList">
                <el-button @click="clickFileUpload(row)" size="mini" type="primary">选择文件</el-button>
              </el-upload>
              <div v-show="row.memo">
                <el-link @click="downloadFile(row)" type="success">下载-{{row.memo}}</el-link>
              </div>
            </div>
          </template>
        </vxe-table-column>
      </vxe-table>
      <vxe-pager :loading="loading" :current-page="page.currentPage" :page-size="page.pageSize" :total="page.totalResult"
        :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']" @page-change="handlePageChange">
      </vxe-pager>
      <!-- 单个打印预览 -->
      <vxe-modal v-model="printModal" title="预览" height="80%" show-zoom resize width="600" show-footer>
        <template #default>
          <otherPlanPrint id="myPrint" :previewData="previewData" :docClassId="currentDocClassId" />
        </template>
        <template #footer>
          <el-button @click="printEvent" type="primary" icon="el-icon-printer" size="mini">打印</el-button>
          <el-button @click="downloadWord" type="primary" icon="iconfont icon-word1" size="mini"> 导出word</el-button>
        </template>
      </vxe-modal>
      <!-- 全部打印预览导出 -->
      <vxe-modal v-model="printWordModal" title="预览" height="80%" show-zoom resize width="600" show-footer>
        <template #default>
          <planWordPrint id="myPrint" :docDataWord="docDataWord" />
        </template>
        <template #footer>
          <el-button @click="printEvent('myPrintAll')" type="primary" icon="el-icon-printer" size="mini">打印</el-button>
          <el-button @click="downloadWord('myPrintAll')" type="primary" icon="iconfont icon-word1" size="mini"> 导出word</el-button>
        </template>
      </vxe-modal>
    </div>
  </div>
</template>

<script>
  import {all4regulationManagement,plan_doc_all,allType,plan_doc_delete,select4regulationDepartment,
  batchPrint,plan_doc_management,plan_doc_select,regulation_fileUpload,doc_class_all,fileDownload} from '@/api/plan.js'
  import {currentRoleEmployee} from '@/api/person.js'
  import {sport_by_org,sport_item,plan_doc_available,docDataId2departmentName,regulation_department} from '@/api/dict.js'
  import otherPlanPrint from "@/components/print/otherPlanPrint.vue"
  import weekPlanPrint from "@/components/print/weekPlanPrint.vue"
  import planWordPrint from '@/components/print/planWordPrint.vue'
  import htmlDocx from 'html-docx-js/dist/html-docx';
  import saveAs from 'file-saver';
  export default {
    components: {
      otherPlanPrint,
      weekPlanPrint,
      planWordPrint
    },
    props: ['docClassId','name','searchName'],
    data() {
      return {
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            },
          },{
            text: '最近一年',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30 * 12);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        defaultDataList: [],
        dataList: [],
        page: {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0
        },
        loading: false,
        filterName: '',
        searchProps: [],
        dict_emp: {},
        dict_sport: {},
        dict_sportItem: {},
        dict_available: {},
        dict_docClass: {
          38: '训练单位训练工作计划',
          39: '训练单位训练工作总结',
          40: '常规管理制度',
          45: '科研工作计划及总结',
          46: '公告和通知',
          47: '反兴奋剂计划及总结',
          48: '教育计划及总结',
          49: '德育计划及总结',
          50: '梯队建设计划及总结',
          51: '训练部门中长期训练规划',
          52: '培训规划及总结',
          53: '各运动队年度工作计划及总结',
        },
        dict_regulation_department: {},
        dict_docDataId2departmentName: {},
        printModal: false,
        previewData: {},
        currentDocClassId: null,
        plan_path: {
          38: '/trainPlan/viewUnitPlan',
          39: '/trainPlan/viewUnitSummary',
          40: '/plan/viewRegulation',
          45: '/trainPlan/viewScience',
          46: '/trainPlan/viewHonorReword',
          47: '/trainPlan/viewAntiDoping',
          48: '/trainPlan/viewEduWorking',
          49: '/trainPlan/viewMoralEducation',
          50: '/trainPlan/viewEchelonConstruction',
          51: '/trainPlan/viewTrainDepartmentMiddleLongPlan',
          52: '/trainPlan/viewTrainPlanAndSummary',
          53: '/trainPlan/viewSportTeamYearPlanAndSummary',
        },
        searchForm: {
          docClassId: null,
          name: null,
          empId: null,
          departmentId: null,
          sportId: null,
          sportItemId: null,
          beginDate: null,
          endDate: null,
        },
        doubleDate: null,
        printWordModal: false,
        checkText: '选择打印',
        fileList: [],
        fileRow: {},
        currentRow: {},
        search: false,
      }
    },
    created() {
      this.init_dict().then(()=>{
        this.getPlanList()
      })
    },
    computed: {
      docmentVisibility() {
        return this.$store.state.app.docmentVisibility;
      },
    },
    watch: {
      filterName(val) {
        if(!val){
          this.page = {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0,
          }
          this.search = false
          this.findList()
        }
      },
      docmentVisibility(newVal) {
        if (!newVal) return;
        this.searchSubmit()
      },
    },
    methods: {
      downloadFile(row){
        row.downloadShow = true
        this.$forceUpdate()
        fileDownload(row.docDataId).then(res=>{
          try {
             var blob = res.data;
            // FileReader主要用于将文件内容读入内存
             var reader = new FileReader();
             reader.readAsDataURL(blob);
             // onload当读取操作成功完成时调用
             reader.onload = function(e) {
               var a = document.createElement('a');
               // 获取文件名fileName
               var fileName = res.headers["content-disposition"].split("=");
               fileName = fileName[fileName.length - 1];
               fileName = fileName.replace(/"/g, "");
               fileName = decodeURI(fileName)
               a.download = fileName;
               a.href = e.target.result;
               document.body.appendChild(a);
               a.click();
               document.body.removeChild(a);
             }
           }catch{
              this.$message.warning('没有找到文件！')
           }
           row.downloadShow = false
           this.$forceUpdate()
        })
      },
      beforeFileUpload(file){
        this.fileRow.downloadShow = true
        if (file.size > 1024 * 1024 * 100) {
          this.fileRow.downloadShow = false
          this.fileRow = {}
          this.fileList = []
          this.$message.error('上传文件太大!不能超过100M');
          return
        }
        let fileName = encodeURI(file.name)
        let fileData = new FormData()
        fileData.append("fileName",this.fileRow.docDataId+"-"+ fileName);
        fileData.append("file", file.raw);
        fileData.append("folderName", this.name);
        regulation_fileUpload(fileData).then(res=>{
          if(res.code === 200) {
            this.fileRow.memo = this.fileRow.docDataId+"-"+ file.name
            this.fileRow.downloadShow = false
            // this.getPlanList()
            this.fileRow = {}
            this.fileList = []
            this.$message.success('上传成功!')
          }else{
            this.$message.error('上传失败!')
            this.fileRow.downloadShow = false
          }
        })
      },
      clickFileUpload(row){
        this.fileRow = row
      },
      exportData() {
        this.getDocDataIdAll()
      },
      exportSelectEvent() {
        if(this.checkText == '选择打印'){
          this.checkText = '取消选择'
          this.$refs.XTable.showColumn(this.$refs.XTable.getColumnByField('checkbox'))
        }else{
          this.checkText = '选择打印'
          this.$refs.XTable.clearCheckboxRow()
          this.$refs.XTable.hideColumn(this.$refs.XTable.getColumnByField('checkbox'))
        }

      },
      getDocDataIdAll() {
        let docDataIdArr = []
        let data = this.$refs.XTable.getCheckboxRecords()
        if(data.length==0){
         this.defaultDataList.forEach(item=>{
           docDataIdArr.push(item.docDataId)
         })
        }else{
          data.forEach(item=>{
            docDataIdArr.push(item.docDataId)
          })
        }
        batchPrint({docDataIds:docDataIdArr.join(',')}).then(res=>{
          if(res.code === 200) {
            this.docDataWord = res.data
            this.printWordModal = true
          }else{
            this.$message.error(res.data)
          }
        })
      },
      searchSubmit() {
        let data = {}
        if(this.searchForm.docClassId) data.docClassId = this.searchForm.docClassId
        if(this.searchForm.empId) data.empId = this.searchForm.empId
        if(this.searchForm.name) data.name = this.searchForm.name
        if(this.searchForm.sportId) data.sportId = this.searchForm.sportId
        if(this.searchForm.departmentId) data.departmentId = this.searchForm.departmentId
        if(this.searchForm.sportItemId) data.sportItemId = this.searchForm.sportItemId
        if (this.doubleDate){
          data.beginDate = this.$moment(this.doubleDate[0]).format('YYYY-MM-DD') + ' 00:00:00'
          data.endDate = this.$moment(this.doubleDate[1]).format('YYYY-MM-DD') + ' 00:00:00'
        }
        if(!this.searchName && !this.docClassId){
          select4regulationDepartment(data).then(res=>{
            if(res.code === 200 && res.data.length != 0) {
              this.page = {
                currentPage: 1,
                pageSize: 10,
                totalResult: 0
              }
              this.init_data(res.data)
            }else{
              this.defaultDataList = []
            }
          }).then(()=>{
            this.findList()
          })
        }else{
          if(this.searchName) {
            plan_doc_management({name:this.searchName,data:data}).then(res=>{
              if(res.code === 200 && res.data.length != 0) {
                this.init_data(res.data)
              }else{
                this.defaultDataList = []
              }
            }).then(()=>{
              this.findList()
            })
          }else{
            plan_doc_select({docClassId:this.docClassId,data:data}).then(res=>{
              if(res.code === 200 && res.data.length != 0) {
                this.init_data(res.data)
              }else{
                this.defaultDataList = []
              }
            }).then(()=>{
              this.findList()
            })
          }
        }

      },
      clearTableFilter() {
        this.searchForm = {
          docClassId: null,
          name: null,
          empId: null,
          sportId: null,
          sportItemId: null,
          beginDate: null,
          endDate: null,
        }
        this.doubleDate = null
        this.getPlanList()
      },
      planDelete(row) {
        this.$confirm('此操作将永久删除该条记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          plan_doc_delete({docDataId:row.docDataId}).then(res=>{
            if(res.code === 200) {
              this.$message.success('删除成功！')
              this.getPlanList()
            }else{
              this.$message.error(res.message)
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      planEdit(row) {
        const { href } = this.$router.resolve({
            path: this.plan_path[row.docClassId],
            query: {docDataId:row.docDataId}
        });
        window.open(href, '_blank');
      },
      downloadWord(myPrintAll) {
        let divEl = ''
        if(myPrintAll=='myPrintAll') {
          divEl = document.getElementById('myPrintAll')
        }else{
          divEl = document.getElementById('myPrint')
        }
        this.page = `<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body>${divEl.innerHTML}</body></html>`
        const converted = htmlDocx.asBlob(this.page);
        // 用 FielSaver.js里的保存方法 进行输出
        saveAs(converted, this.currentRow.name+'.docx');
      },
      printEvent(myPrintAll) {
        let divEl = ''
        if(myPrintAll=='myPrintAll') {
          divEl = document.getElementById('myPrintAll')
        }else{
          divEl = document.getElementById('myPrint')
        }
        this.$XPrint({
          sheetName: '',
          content: divEl.innerHTML
        })
      },
      printModalShow(row) {
        this.currentRow = row
        this.currentDocClassId = row.docClassId
        allType({docDataId:row.docDataId,docClassId:row.docClassId}).then(res=>{
          if(res.code === 200) {
            this.previewData = res.data
            this.printModal = true
          }else{
            this.$message.error(res.message)
          }
        })
      },
      getPlanList() {
        if(!this.docClassId){
          all4regulationManagement().then(res=>{
            if(res.code === 200) {
               this.init_data(res.data)
            }else{
              this.defaultDataList = []
             this.$message.error(res.message)
            }
          }).then(()=>{
            this.findList()
            this.$refs.XTable.hideColumn(this.$refs.XTable.getColumnByField('checkbox'))
          })
        }else{
          if(!this.name){
            plan_doc_all(this.docClassId).then(res=>{
              if(res.code === 200) {
                 this.init_data(res.data)
              }else{
                this.defaultDataList = []
               this.$message.error(res.message)
              }
            }).then(()=>{
              this.findList()
              this.$refs.XTable.hideColumn(this.$refs.XTable.getColumnByField('checkbox'))
            })
          }else{
            plan_doc_management({name:this.name}).then(res=>{
              if(res.code === 200) {
                 this.init_data(res.data)
              }else{
                this.defaultDataList = []
               this.$message.error(res.message)
              }
            }).then(()=>{
              this.findList()
              this.$refs.XTable.hideColumn(this.$refs.XTable.getColumnByField('checkbox'))
            })
          }
        }
      },
      init_data(data) {
        if(data.length==0) return
        data.forEach(item=>{
          item.emp = this.dict_emp[item.empId]
          item.available = this.dict_available[item.docClassId]
          item.sport = this.dict_sport[item.sportId]
          item.spoetItem = this.dict_sportItem[item.sportItemId]
          item.createDate = this.$moment(item.createDate).format('YYYY-MM-DD')
          item.closeDate = this.$moment(item.closeDate).format('YYYY-MM-DD')
          item.openDate = this.$moment(item.openDate).format('YYYY-MM-DD')
          item.status = item.statusId == 1 ? "正式" : "草稿"
          item.departmentName = this.dict_docDataId2departmentName[item.docDataId]
          if(item.memo){
            let arr = item.memo.split(',')
            let memoArr = []
            arr.forEach(memo=>{
              memoArr.push(this.dict_emp[memo])
            })
            item.memoName = memoArr.join(',')
          }
        })
        if(data[0]){
          this.searchProps = Object.keys(data[0])
        }
        this.defaultDataList = data
      },
      init_dict() {
        return new Promise((resolve,reject)=>{
          regulation_department().then(res=>{
            this.dict_regulation_department = res
          })
          currentRoleEmployee().then(res=>{
            res.data.forEach(item=>{
              this.dict_emp[item.empId] = item.name
            })
            // sport_by_org().then(res=>{
            //   this.dict_sport = res
            // })
            // sport_item().then(res=>{
            //   this.dict_sportItem = res
            // })
            // plan_doc_available().then(res=>{
            //   this.dict_available = res
            // })
          })
          docDataId2departmentName().then(res=>{
            this.dict_docDataId2departmentName = res
            resolve()
          })
        })
      },
      searchEvent() {
        const filterName = this.$XEUtils.toValueString(this.filterName).trim().toLowerCase()
        if (filterName) {
          const filterRE = filterName
          const searchProps = this.searchProps
          const rest = this.defaultDataList.filter(item => searchProps.some(key => this.$XEUtils.toValueString(item[
            key]).toLowerCase().indexOf(filterName) > -1))
          this.dataList = rest.map(row => {
            const item = Object.assign({}, row)
            searchProps.forEach(key => {
              item[key] = this.$XEUtils.toValueString(item[key]).replace(filterRE, match => match)
            })
            return item
          })
          this.page = {
            currentPage: 1,
            pageSize: this.dataList.length,
            totalResult: this.dataList.length
          }
          this.search = true
        } else {
          this.dataList = this.defaultDataList
     }
      },
      handlePageChange({
        currentPage,
        pageSize
      }) {
        this.page.currentPage = currentPage
        this.page.pageSize = pageSize
        this.findList()
      },
      sortChange() {
      	if(!this.search){
          this.page.currentPage = 1
      	  this.page.pageSize = this.defaultDataList.length
      	  this.findList()
      	}else{
      	  this.page.pageSize = this.dataList.length
      	}
      },
      findList() {
        this.loading = true
        setTimeout(() => {
          if(this.insertSuccess){
            this.page.totalResult = this.defaultDataList.length
            this.page.currentPage = Math.ceil(this.page.totalResult/this.page.pageSize)
            this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
              .pageSize, this.page.currentPage * this.page.pageSize)
            this.$refs.XTable.setCurrentRow(this.dataList[this.dataList.length-1])
            this.insertSuccess = false
          }else{
            this.page.totalResult = this.defaultDataList.length
            this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
              .pageSize, this.page.currentPage * this.page.pageSize)
          }
          this.loading = false
        }, 300)
      },
    }
  }
</script>

<style lang="scss" scoped>
  .body{
    padding: 10px;
    background-color: #FFFFFF;
  }
</style>
